package com.cn.yang.util;//package com.cn.yang.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
   }

   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       HttpServletRequest req = (HttpServletRequest) servletRequest;
       HttpServletResponse resp = (HttpServletResponse) servletResponse;
       req.setCharacterEncoding("UTF-8");
       resp.setCharacterEncoding("UTF-8");
//       resp.setHeader("Access-Control-Allow-Origin", "http://localhost:63343");
//       resp.setHeader("Access-Control-Allow-Credentials", "true");

       resp.setHeader("Access-Control-Allow-Origin", "*");
       resp.setHeader("Access-Control-Allow-Credentials", "true");
//       resp.setHeader("Access-Control-Allow-Headers", "content-type, accept");
//       resp.setHeader("Access-Control-Allow-Headers", "file:///F:/WebStormProject/SSM-01/*");
//       resp.setHeader("Access-Control-Expose-Headers", "*");
//       if (resp.getMethod().equals("OPTIONS")) {
//           HttpUtil.setResponse(response, HttpStatus.OK.value(), null);
//           return;
//       }

       String url = req.getServletPath();
       System.out.println(url);
       if (url.startsWith("/back/")){
           if(url.endsWith("css")||url.endsWith("js")||url.endsWith("regester")){
               filterChain.doFilter(servletRequest,servletResponse);
           }else {

               String username = (String) req.getSession().getAttribute("username");
               if (username==null){
                   // resp.sendRedirect("http://localhost:8066/login.html");
                   // req.getRequestDispatcher("http://localhost:8066/login.html").forward(req,resp);
                   resp.getWriter().println(400);
               }else {
                   System.out.println("Filter1");
                   filterChain.doFilter(servletRequest,servletResponse);
               }
           }
       }else {
           System.out.println("Filter2");
           filterChain.doFilter(servletRequest,servletResponse);
       }
//        filterChain.doFilter(servletRequest,servletResponse);

   }

   @Override
   public void destroy() {

   }
}
